<template>
  <a-modal
    v-model:visible="showModal"
    @close="onClose"
    @before-ok="submitFn"
    title="结算"
    class="modal-dialog-wrapper"
    unmount-on-close
    :mask-closable="false"
    width="65vw"
  >
    <div class="fee-page">
      <div class="fee-list">
        <div style="margin: 0 20px">
          <div class="fee-tlt">
            <div class="tlt-name">
              <span class="tag-name">年检费</span>
              <span class="tag-cost">付款</span>
            </div>
            <div class="tlt-price">应付：{{ unitVal(feeRecord.totalAmount, '元') }}</div>
          </div>
          <div style="margin-bottom: 24px">
            <div class="fee-msg">
              <div class="msg">
                <div class="msg-tlt">
                  <span>{{ settlementTypeName }}单号：</span>{{ feeRecord.businesCode || '-' }}
                </div>
                <div class="msg-tlt">
                  <span>{{ supplierTypeName }}：</span>{{ feeRecord.supplier || '-' }}
                </div>
                <div class="msg-tlt"><span>车牌号：</span>{{ feeRecord.licenseNo || '-' }}</div>
                <div class="msg-tlt"><span>本次年检日期：</span>{{ feeRecord.businesTime || '-' }}</div>
                <div class="msg-tlt"><span>费用备注：</span>{{ feeRecord.feeRemark || '-' }}</div>
              </div>
              <div class="msg-open" @click="foldChange(false)" v-if="isFold">收起 <icon-up /></div>
              <div class="msg-open" @click="foldChange(true)" v-else>展开 <icon-down /></div>
            </div>
            <div class="amount-all" v-if="isFold">
              <div class="line">
                <div></div>
              </div>
              <div class="amount"> 待付：{{ unitVal(feeRecord.totalAmount, '元') }} </div>
            </div>
          </div>
        </div>

        <div class="all-cost">
          <span>合计</span>
          <div class="cost-num">
            <div>应付：{{ unitVal(Math.abs(feeRecord.totalAmount), '元') }}</div>
            <div style="margin-top: 16px">待付：{{ unitVal(Math.abs(feeRecord.totalAmount), '元') }}</div>
          </div>
        </div>
      </div>

      <page-form :model="form" layout="vertical" ref="formRef" style="margin-top: 24px">
        <page-form-row>
          <page-form-item field="paymentTime" label="结算时间" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
            <i-date-picker class="w-full" v-model="form.paymentTime" show-time value-format="YYYY-MM-DD HH:mm:ss" />
          </page-form-item>
          <page-form-item
            field="paymentWay"
            label="结算方式"
            :rules="{ required: true, message: '请选择' }"
            labelTooltipContent="收/付款方式支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select placeholder="请选择" v-model="form.paymentWay" @change="typeChange" popup-container=".fee-page">
              <a-option v-for="item in paywayEnum" :key="item.way" :value="item.way" :label="item.wayStr" />
            </a-select>
          </page-form-item>
          <page-form-item
            field="account"
            label="结算账号"
            labelTooltipContent="收/付款账号支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select
              :placeholder="!form.paymentWay ? '请先选择结算方式' : '请选择'"
              v-model="form.account"
              :disabled="!form.paymentWay ? true : false"
              popup-container=".fee-page"
            >
              <a-option
                v-for="item in accountList"
                :key="item.id"
                :value="item.id"
                :label="item.account + (item.bank ? '_' + item.bank : '')"
              />
            </a-select>
          </page-form-item>
          <page-form-item field="actualAmount" label="结算金额" :rules="{ required: true, message: '请输入结算金额' }">
            <i-input-number v-model="form.actualAmount" unit="元" :precision="2" disabled />
          </page-form-item>
          <page-form-item v-if="settlementType == 3" field="locationId" label="年检厂名称" :rules="{ required: true, message: '请选择' }">
            <template #label-extra>
              <i-add-supplier typeText="年检" supplierType="1" @addOk="addSupplierOk" />
            </template>
            <remote-select
              v-model="form.customerId"
              type="supplier_list"
              :params="{
                status: 1,
                idList: [form.customerId],
                supplierType: 6,
                refreshSupplierSelect,
              }"
              @change="supplierChange"
            />
          </page-form-item>
          <page-form-item v-else field="locationId" label="修理厂名称" :rules="{ required: true, message: '请选择' }">
            <template #label-extra>
              <i-add-supplier typeText="保养" supplierType="1" @addOk="addSupplierOk" />
            </template>
            <remote-select
              v-model="form.customerId"
              type="supplier_list"
              :params="{
                status: 1,
                idList: [form.customerId],
                supplierType: 1,
                refreshSupplierSelect,
              }"
              @change="supplierChange"
            />
          </page-form-item>
          <page-form-item field="customerAccount" :label="supplierTypeName + '收款账号'">
            <i-input placeholder="请输入" v-model="form.customerAccount" :max-length="20" />
          </page-form-item>
          <page-form-item field="settlementRemark" label="结算备注" size="2/3">
            <i-input textarea placeholder="请输入" v-model="form.settlementRemark" :max-length="200" />
          </page-form-item>
          <page-form-item label="打款凭证（支持上传jpg、png格式，最多上传10张）" size="1">
            <upload-img v-model="form.fileIdList" :limit="10" />
          </page-form-item>
        </page-form-row>
      </page-form>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="onClose">关闭</a-button>
        <a-button type="primary" @click="submitFn" :loading="okLoading">确认</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup>
  //  保养\年检 确认费用
  import { Message } from '@arco-design/web-vue'
  import { unitVal } from '@/utils'
  import { getAccountByPageData, getAccountByWayAndType } from '@/api/order/sOrder'
  import { confirmOrderFee } from '@/api/finance/costConfirm'
  import { supplierDetail } from '@/api/market/supplier'
  import { ref } from 'vue'

  const costType = ref(null) // type  0-收款，1-付款
  const paywayEnum = ref([]) //收付款方式
  const accountList = ref([]) //收付款账号列表
  const formRef = ref(null)

  // 打开弹窗
  const showModal = ref(false)
  const form = ref({})
  const feeRecord = ref({})
  const supplierTypeName = ref('')
  const settlementTypeName = ref('')
  const settlementType = ref(null) // settlementType_vlaue 结算类型  1保养 3年检 同supplierType

  const show = (record_value, settlementType_vlaue) => {
    settlementType.value = settlementType_vlaue
    showModal.value = true
    form.value.idList = [record_value.id]
    if (settlementType_vlaue == 1) {
      supplierTypeName.value = '维修厂'
      settlementTypeName.value = '保养'
      feeRecord.value = {
        businesCode: record_value.maintenanceNo,
        supplier: record_value.maintenanceShop,
        licenseNo: record_value.licenseNo,
        businesTime: record_value.entranceDate,
        feeRemark: record_value.feeRemark,
        totalAmount: record_value.maintenanceAmount,
      }
      form.value = {
        idList: [record_value.id],
        paymentTime: record_value.createTime,
        paymentWay: undefined,
        account: undefined,
        actualAmount: record_value.maintenanceAmount,
        customerId: record_value.maintenanceShopId,
        customerName: record_value.maintenanceShop,
        customerAccount: undefined,
        settlementRemark: undefined,
      }
    } else {
      supplierTypeName.value = '年检厂'
      settlementTypeName.value = '年检'
      feeRecord.value = {
        businesCode: record_value.inspectionNo,
        supplier: record_value.location,
        licenseNo: record_value.licenseNo,
        businesTime: record_value.inspectionTime,
        feeRemark: record_value.feeRemark,
        totalAmount: record_value.inspectionAmount,
      }
      form.value = {
        idList: [record_value.id],
        paymentTime: record_value.createTime,
        paymentWay: undefined,
        account: undefined,
        actualAmount: record_value.inspectionAmount,
        customerId: record_value.locationId,
        customerName: record_value.location,
        customerAccount: undefined,
        settlementRemark: undefined,
      }
    }
    // 获取收支类型
    getTypeList()
  }
  const onClose = () => {
    showModal.value = false
    // 重置
    resetForm()
  }
  const resetForm = () => {
    paywayEnum.value = []
    accountList.value = []
    feeRecord.value = {}
    form.value = {}
  }

  // 收付款类型
  const getTypeList = () => {
    getAccountByPageData({ type: 0 }).then((res) => {
      // 过滤
      var data = res.result
      data.forEach((i) => {
        if (i.way != '1' && i.way != '2' && i.way != '3' && i.way != '4' && i.way != '5') {
          paywayEnum.value.push(i)
        }
      })
    })
  }
  // 账号
  const typeChange = (e) => {
    if (e) {
      form.value.account = ''
    }
    paywayEnum.value.forEach((el) => {
      if (el.way == e) {
        getAccountByWayAndType({ way: Number(el.way), type: costType.value == 0 ? 0 : 1 }).then((res) => {
          accountList.value = res.result
        })
      }
    })
  }

  // 添加厂商 before
  const refreshSupplierSelect = ref(0)
  const addSupplierOk = (id) => {
    form.value.customerId = id
    refreshSupplierSelect.value++
    supplierDetail({ id: id }).then((res) => {
      form.value.customerName = res.result.supplierName
    })
  }
  const supplierChange = (e, option = {}) => {
    form.value.customerName = option.supplierName
  }
  // 获取厂商 end

  const emit = defineEmits(['feepageConfirm'])
  const okLoading = ref(false)
  const submitFn = () => {
    okLoading.value = true
    formRef.value.validate((error) => {
      if (!error) {
        const param = {
          ...form.value,
        }
        confirmOrderFee(param)
          .then((res) => {
            okLoading.value = false
            Message.success(res.message)
            showModal.value = false
            emit('feepageConfirm')
          })
          .finally(() => {
            okLoading.value = false
          })
      } else {
        okLoading.value = false
      }
    })
  }

  const isFold = ref(true)
  const foldChange = (v) => {
    isFold.value = v
  }

  defineExpose({
    show,
  })
</script>

<style lang="less" scoped>
  .fee-list {
    padding-top: 20px;
    border: 1px solid #f2f3f5;
  }
  .all-cost {
    font-weight: 600;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    background: #f2f3f5;
    height: 100px;
    .cost-num {
      color: #1890ff;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
    }
  }
  // 弹窗添加的样式
  .fee-page {
    width: 100%;
    max-height: 70vh;
    position: relative;

    :deep(.arco-row) {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }
    :deep(.arco-modal-body) {
      padding: 10px 80px !important;
    }
    :deep(.arco-col) {
      padding: 0 10px !important;
    }
  }

  .fee-tlt {
    width: 100%;
    height: 40px;
    background-color: #f2f3f5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .tlt-name {
      .tag-name {
        font-weight: 600;
        font-size: 14px;
        margin-left: 20px;
      }
      .tag-online {
        font-size: 12px;
        padding: 0 8px;
        border-radius: 2px;
        border: 1px solid #3491fa;
        color: #3491fa;
        background: #e8f7ff;
        margin-left: 12px;
      }
      .tag-cost {
        font-size: 12px;
        padding: 0 8px;
        border-radius: 2px;
        border: 1px solid #ff7d00;
        color: #ff7d00;
        background: #fff7e8;
        margin-left: 12px;
      }
    }
    .tlt-price {
      font-size: 14px;
      color: #1890ff;
      font-weight: 600;
      margin-right: 20px;
    }
  }

  .fee-msg {
    background: #fbfbfc;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    width: 100%;
    padding-top: 20px;
    .msg {
      flex: 1;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-wrap: wrap;
      margin-left: 20px;
      div {
        width: 33.33%;
        margin-bottom: 12px;
      }
      .msg-tlt {
        color: var(--color-neutral-10);
        span {
          color: var(--color-neutral-8);
        }
      }
      .times {
        width: 66.66%;
      }
    }
    .msg-open {
      width: 50px;
      color: #1890ff;
      font-size: 14px;
      margin-right: 20px;
      cursor: pointer;
    }
  }
  .amount-all {
    background-color: #fbfbfc;
    .amount {
      width: 100%;
      padding-bottom: 24px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding-right: 20px;
    }
  }
</style>
